"use client";

import React, { useState, useEffect } from 'react';
import AdminGuard from '@/components/layout/AdminGuard';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from '@/components/ui/dialog';
import { getProducts } from '@/lib/api';
import { Product } from '@/types/Product';

const AdminPage = () => {
    const [products, setProducts] = useState<Product[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
    const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
    const [uploading, setUploading] = useState(false);

    const [newProduct, setNewProduct] = useState({
        name: '',
        description: '',
        price: 0,
        category: '',
        imageUrl: ''
    });

    const fetchProducts = async () => {
        setIsLoading(true);
        try {
            const data = await getProducts();
            setProducts(data);
        } catch (error) {
            console.error("Failed to fetch products", error);
            alert("获取商品列表失败。");
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchProducts();
    }, []);

    const handleNewProductInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setNewProduct(prev => ({ ...prev, [name]: name === 'price' ? parseFloat(value) || 0 : value }));
    };

    const handleEditProductInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        if (!selectedProduct) return;
        const { name, value } = e.target;
        setSelectedProduct(prev => prev ? ({ ...prev, [name]: name === 'price' ? parseFloat(value) || 0 : value }) : null);
    };

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>, setState: React.Dispatch<React.SetStateAction<any>>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        setUploading(true);
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch('/api/admin/products/upload-image', {
                method: 'POST',
                body: formData,
            });

            if (!response.ok) {
                throw new Error('Image upload failed');
            }

            const data = await response.json();
            setState((prev: any) => ({ ...prev, imageUrl: data.imageUrl }));
            alert("图片上传成功！");
        } catch (error) {
            console.error(error);
            alert('图片上传失败。');
        } finally {
            setUploading(false);
        }
    };

    const handleAddProduct = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const response = await fetch('/api/admin/products', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(newProduct)
            });
            if (!response.ok) throw new Error('Failed to add product');
            alert('商品添加成功！');
            setNewProduct({ name: '', description: '', price: 0, category: '', imageUrl: '' });
            fetchProducts();
        } catch (error) {
            console.error(error);
            alert('添加商品失败。');
        }
    };

    const handleDeleteProduct = async (productId: string) => {
        if (!window.confirm("您确定要删除这个商品吗？")) return;
        try {
            const response = await fetch(`/api/admin/products/${productId}`, { method: 'DELETE' });
            if (!response.ok) throw new Error('Failed to delete product');
            alert('商品删除成功！');
            fetchProducts();
        } catch (error) {
            console.error(error);
            alert('删除商品失败。');
        }
    };

    const handleEditProduct = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedProduct) return;
        try {
            const response = await fetch(`/api/admin/products/${selectedProduct.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(selectedProduct)
            });
            if (!response.ok) throw new Error('Failed to update product');
            alert('商品更新成功！');
            setIsEditDialogOpen(false);
            fetchProducts();
        } catch (error) {
            console.error(error);
            alert('更新商品失败。');
        }
    };

    const openEditDialog = (product: Product) => {
        setSelectedProduct(product);
        setIsEditDialogOpen(true);
    };
    
    return (
        <AdminGuard>
            <div className="container mx-auto p-4 space-y-8">
                <div>
                    <h1 className="text-3xl font-bold mb-4">商品管理</h1>
                    <Card>
                        <CardHeader><CardTitle>添加新商品</CardTitle></CardHeader>
                        <CardContent>
                            <form onSubmit={handleAddProduct} className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <Input name="name" placeholder="名称" value={newProduct.name} onChange={handleNewProductInputChange} required />
                                <Input name="category" placeholder="类别" value={newProduct.category} onChange={handleNewProductInputChange} required />
                                <Textarea name="description" placeholder="描述" value={newProduct.description} onChange={handleNewProductInputChange} required className="md:col-span-2" />
                                <Input name="price" type="number" placeholder="价格" value={newProduct.price} onChange={handleNewProductInputChange} required />
                                <div>
                                    <Label htmlFor="new-image-upload">商品图片</Label>
                                    <Input id="new-image-upload" type="file" onChange={(e) => handleFileChange(e, setNewProduct)} disabled={uploading} />
                                    {uploading && <p className="text-sm text-muted-foreground mt-1">正在上传...</p>}
                                    {newProduct.imageUrl && <img src={newProduct.imageUrl} alt="Preview" className="mt-2 h-24 w-24 object-cover rounded-md" />}
                                </div>
                                <Button type="submit" className="md:col-span-2" disabled={uploading}>
                                    {uploading ? '正在上传图片...' : '确认添加'}
                                </Button>
                            </form>
                        </CardContent>
                    </Card>
                </div>

                <div>
                    <h2 className="text-2xl font-bold mb-4">现有商品列表</h2>
                    {isLoading ? <p>正在加载商品...</p> : (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            {products.map(product => (
                                <Card key={product.id}>
                                    <CardHeader>
                                        <CardTitle>{product.name}</CardTitle>
                                        <CardDescription>{product.category} - ¥{product.price}</CardDescription>
                                    </CardHeader>
                                    <CardContent>
                                        <img src={product.imageUrl} alt={product.name} className="w-full h-48 object-cover rounded-md mb-4" />
                                        <p>{product.description}</p>
                                    </CardContent>
                                    <CardFooter className="flex justify-end gap-2">
                                        <Button variant="outline" onClick={() => openEditDialog(product)}>编辑</Button>
                                        <Button variant="destructive" onClick={() => handleDeleteProduct(product.id)}>删除</Button>
                                    </CardFooter>
                                </Card>
                            ))}
                        </div>
                    )}
                </div>
            </div>

            {selectedProduct && (
                <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>编辑商品: {selectedProduct.name}</DialogTitle>
                            <DialogDescription>在此处修改商品信息。</DialogDescription>
                        </DialogHeader>
                        <form onSubmit={handleEditProduct} className="space-y-4">
                            <div>
                                <Label htmlFor="name">商品名称</Label>
                                <Input id="name" name="name" value={selectedProduct.name} onChange={handleEditProductInputChange} />
                            </div>
                            <div>
                                <Label htmlFor="description">描述</Label>
                                <Textarea id="description" name="description" value={selectedProduct.description} onChange={handleEditProductInputChange} />
                            </div>
                            <div>
                                <Label htmlFor="price">价格</Label>
                                <Input id="price" name="price" type="number" value={selectedProduct.price} onChange={handleEditProductInputChange} />
                            </div>
                             <div>
                                <Label htmlFor="category">类别</Label>
                                <Input id="category" name="category" value={selectedProduct.category} onChange={handleEditProductInputChange} />
                            </div>
                            <div>
                                <Label htmlFor="edit-image-upload">商品图片</Label>
                                <Input id="edit-image-upload" type="file" onChange={(e) => handleFileChange(e, setSelectedProduct)} disabled={uploading} />
                                {uploading && <p className="text-sm text-muted-foreground mt-1">正在上传...</p>}
                                {selectedProduct.imageUrl && <img src={selectedProduct.imageUrl} alt="Preview" className="mt-2 h-24 w-24 object-cover rounded-md" />}
                            </div>
                            <DialogFooter>
                                <DialogClose asChild><Button type="button" variant="secondary">取消</Button></DialogClose>
                                <Button type="submit" disabled={uploading}>
                                    {uploading ? '正在上传图片...' : '保存更改'}
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>
            )}
        </AdminGuard>
    );
};

export default AdminPage; 